<template>
  <div class="flex mt-6">
    <transition name="list">
      <Cropper
        v-if="showCropper"
        :src="tempURL"
        @closeCropper="closeCropper"
        :content="content"
        :mime="mime"
        :type="filetype"
        :resizeImage="resizeImage"
      />
    </transition>
    <div class="flex flex-wrap items-center">
      <img
        class="w-12 h-12 rounded object-contain"
        v-if="imageAttached && !isVideo"
        :src="content[type].url"
        :title="`${
          type == 'logo'
            ? 'Brand logo'
            : type == 'photo'
            ? 'Card holder\'s photo'
            : 'Cover image'
        }`"
      />
      <video
        class="w-12 h-12 rounded object-contain"
        v-if="imageAttached && isVideo"
        :src="content[type].url"
        :title="`${
          type == 'logo'
            ? 'Brand logo'
            : type == 'photo'
            ? 'Card holder\'s photo'
            : 'Cover video'
        }`"
        muted
        loop
        autoplay
      />
      <button
        v-if="!imageAttached"
        class="p-3 rounded bg-gray-700 cursor-pointer hover:bg-gray-600 focus:bg-gray-600 transition-colors duration-200 focus:outline-none"
        @click="attachFile(null, type, false)"
        :class="
          dragOver ? 'bg-gray-900 outline-white' : 'bg-gray-700 border-none'
        "
        :aria-label="label"
        @drop.prevent="attachFile($event, type, true)"
        @dragleave.prevent.self="dragOver = false"
        @dragover.prevent.self="dragOver = true"
      >
        <input
          :ref="`import${type}`"
          type="file"
          :accept="`.png,.jpg,.jpeg,.gif,.webp${
            type == 'logo' || type == 'cover' ? ',.svg' : ''
          }${
            type == 'cover' ? ',.mp4,.webm,.mov' : ''
          }`"
          v-show="false"
          @change="fileLoaded($event, type, false)"
          @click="$event.target.files = null"
        />
        <div
          class="w-6 h-6 pointer-events-none"
          v-html="require(`~/assets/icons/add.svg?include`)"
        ></div>
      </button>
      <p v-if="!imageAttached" class="ml-3 leading-none">
        {{ label
        }}<span class="text-sm text-gray-400"><br />{{ description }}</span>
      </p>
      <button
        v-else
        class="p-1 m-2 shrink-0 focus:outline-none rounded hover:bg-gray-700 focus:bg-gray-700 transition-colors duration-200"
        @click="content[type].url = null"
        :aria-label="`Remove ${type}`"
        :title="`Remove ${type}`"
      >
        <div
          class="w-6 h-6"
          v-html="require(`~/assets/icons/x.svg?include`)"
        ></div>
      </button>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import { uploadConfig } from '~/services/api.config'

export default {
  props: [
    'content',
    'type',
    'label',
    'description',
    'resizeImage',
    'showAlert',
  ],
  data() {
    return {
      dragOver: false,
      showCropper: false,
      tempURL: null,
      mime: null,
      filetype: null,
    }
  },
  computed: {
    imageAttached() {
      return this.content[this.type].url ? true : false
    },
    isVideo() {
      return this.content[this.type].mime && this.content[this.type].mime.startsWith('video/')
    },
  },
  methods: {
    closeCropper() {
      this.showCropper = false
    },
    attachFile(e, type, dropped) {
      dropped
        ? (this.fileLoaded(e, type, true), (this.dragOver = false))
        : this.$refs[`import${type}`].click()
    },
    fileLoaded(e, type, dropped) {
      if (
        (dropped && e.dataTransfer.files.length) ||
        (!dropped && e.target.files.length)
      ) {
        let file = dropped ? e.dataTransfer.files[0] : e.target.files[0]
        let mime = file.type
        if (
          (type == 'logo' || type == 'cover') &&
          file.type.match(/image\/(svg\+xml|png|jpeg|gif|webp)/)
        ) {
          this.imageLoaded(file, type, mime)
        } else if (type == 'cover' && file.type.match(/video\/(mp4|webm|quicktime)/)) {
          this.imageLoaded(file, type, mime)
        } else if (file.type.match(/image\/(png|jpeg|gif|webp)/)) {
          this.imageLoaded(file, type, mime)
        } else {
          if (type == 'logo') {
            this.showAlert(
              'Unsupported file format.\nOnly jpeg, png, webp, gif and svg file can be attached.'
            )
          } else if (type == 'cover') {
            this.showAlert(
              'Unsupported file format.\nOnly jpeg, png, webp, gif, svg, mp4, webm and mov file can be attached.'
            )
          } else {
            this.showAlert(
              'Unsupported file format.\nOnly jpeg, png, webp and gif file can be attached.'
            )
          }
        }
      }
    },
    async imageLoaded(file, type, mime) {
      console.log(type, mime)
      
      try {
        // 创建 FormData 对象
        const formData = new FormData()
        formData.append('file', file)
        
        // 上传文件到接口
        const response = await axios.post(
          uploadConfig.uploadUrl,
          formData,
          {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          }
        )
        
        // 检查响应
        if (response.data && response.data.code === 0) {
          const uploadedUrl = response.data.data.url
          const ext = file.name.split('.').pop()
          
          if (type == 'logo' || mime.match(/svg|gif|webp/) || mime.startsWith('video/')) {
            this.content[type] = {
              url: uploadedUrl,
              blob: file,
              ext,
              mime,
              resized: file,
            }
            if (!mime.match(/svg|gif|webp/) && !mime.startsWith('video/')) this.resizeImage(type, mime)
          } else {
            this.content[type].ext = ext
            this.filetype = type
            this.mime = mime
            this.tempURL = uploadedUrl
            this.showCropper = true
          }
        } else {
          this.showAlert('File upload failed. Please try again.')
        }
      } catch (error) {
        console.error('Upload error:', error)
        this.showAlert('File upload failed. Please try again.')
      }
    },
  },
}
</script>
